using System;
using System.Linq;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;

namespace WebSMS;

public class UserDepartmentLinksService : ITerUserDepartmentLinks,ITransient
{
    private readonly IRepository<UserDepartmentLinks> _repo;
    private readonly IRepository<PostPo> _postDepartmentLinks;
    private readonly IRepository<UserPostLinks> _userPostLinks;
    public UserDepartmentLinksService(IRepository<UserDepartmentLinks> repository, IRepository<PostPo> postDepartmentLinks)
    {
        _repo = repository;
        _postDepartmentLinks = postDepartmentLinks;
    }
    public async Task<bool> AddUserToDepartment(Guid userId, Guid departmentId)
    {
        await _repo.InsertNowAsync(new UserDepartmentLinks()
        {
            Id = Guid.NewGuid(), 
            DepartmentId = departmentId, 
            UserId = userId, 
            CreateTime = DateTime.Now.ToString()
        });
       return true;
    }

    public async Task<bool> DelUserForDepartment(Guid userId, Guid departmentId)
    {
     var user =  await _repo.FirstOrDefaultAsync(ud => ud.UserId == userId && ud.DepartmentId == departmentId);
     if(user!= null)
     {
         await _repo.DeleteNowAsync(user);
         return true;
     }
     return false;
    }

    public async Task<bool> DeleteDepartment(Guid id)
    {
        var post = await _postDepartmentLinks.FirstOrDefaultAsync(pd=> pd.DepartmentId == id);
        var user = _userPostLinks.FirstOrDefaultAsync(up => up.PostId == post.Id);
        if(user != null)
        {
            return true;
        }
        return false;
    }
    
}